<?php

namespace App\Http\Controllers\Api;

use App\Spec;
use App\SpecGoodsImage;
use App\SpecGoodsPrice;
use App\SpecItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SpecController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $orderBy = $request->order_by ? $request->order_by : $this->orderBy;
        $orderType = $request->order_type ? $request->order_type : $this->orderType;
        $pageSize = $request->page_size ? $request->page_size : $this->pageSize;
        $lists = Spec::orderBy($orderBy, $orderType);
        if ($request->name) {
            $lists->where('name', 'like', '%'.$request->name.'%');
        }
        if ($request->type_id) {
            $lists->where('type_id', $request->type_id);
        }
        return $lists->with(['type', 'items'])->paginate($pageSize);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $spec = Spec::create($request->all());

        if ($spec && $request->items) {
            $items = [];
            foreach($request->items as $item) {
                if ($item && $item['item'] != '')
                   $items[] = new SpecItem(['item' => trim($item['item'])]);
            }
            $items = array_unique($items);
            if (count($items) > 0)
                $spec->items()->saveMany($items);
        }
        return response(['message' => '创建成功']);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Spec  $spec
     * @return \Illuminate\Http\Response
     */
    public function show(Spec $spec)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Spec  $spec
     * @return \Illuminate\Http\Response
     */
    public function edit(Spec $spec)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Spec  $spec
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Spec $spec)
    {
        $spec->update($request->all());
        $requestItems = [];
        foreach ($request->items as $item) {
           if ($item && $item['item'] != '') {
               $requestItems[] = trim($item['item']);
           }
        }
        $dbItems = SpecItem::where('spec_id', $spec->id)->select('id', 'item')->get();
        /* 提交过来的跟数据库中比较，不存在则插入*/
        foreach($requestItems as $item) {
            if (!in_array($item, $dbItems->pluck('item')->toArray())) {
                $spec->items()->create(['item' => $item]);
            }
        }

        /* 数据库中的跟提交过来的比较, 不存在则删除, 同时删除规格项对应商品价格*/
        foreach($dbItems as $item) {
            if (!in_array($item->item, $requestItems)) {
                SpecGoodsPrice::where('key', 'like', "{$item->id}_%")
                    ->orWhere('key', 'like', "%_{$item->id}_%")
                    ->orWhere('key', 'like',"%_{$item->id}")
                    ->orWhere('key', "{$item->id}")
                    ->delete();
                $item->delete();
            }
        }
        return response(['message' => '保存成功']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Spec  $spec
     * @return \Illuminate\Http\Response
     */
    public function destroy(Spec $spec)
    {
        foreach ($spec->items as $item) {
            SpecGoodsPrice::where('key', 'like', "{$item->id}_%")
                ->orWhere('key', 'like', "%_{$item->id}_%")
                ->orWhere('key', 'like',"%_{$item->id}")
                ->orWhere('key', "{$item->id}")
                ->delete();
            $item->delete();
        }
        $spec->delete();
        return response(['message' => '删除成功']);
    }

    /**
     * @param Request $request
     * @return array|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function byTypeAndGoods(Request $request)
    {
        if (!$request->type_id) {
            return response(['message' => '非法操作']);
        }
        // 指定模型对应的规格列表
        $specs = Spec::where('type_id', $request->type_id)->with('items')->get();
        // 指定商品所拥有的模型
        $goodsItems = SpecGoodsPrice::where('goods_id', $request->goods_id ? $request->goods_id : 0)->value(DB::raw("GROUP_CONCAT(`key` SEPARATOR '_')"));
        $goodsItems = array_values(array_unique(explode('_', $goodsItems)));

        $arr = [];
        foreach($specs as $spec) {
           $arr[$spec->id] = [];
            foreach($spec->items as $item) {
                $item->image = SpecGoodsImage::where('goods_id', $request->goods_id)->where('spec_item_id', $item->id)->first();
                if (in_array($item->id, $goodsItems))
                    $arr[$spec->id][] = $item->id;
            }
        }
        return ['specs' => $specs, 'goodsSpecItems' => $arr];
    }

    /**
     * 根据商品部同规格，组合不同价
     * @param Request $request （GoodsSpecitems、 goods_id）
     * @return array
     */
    public function specPriceInput(Request $request)
    {
//        $specArr = [
//            2 => [1, 3, 4],
//            5 => [2, 6],
//            8 => [9, 18]
//        ];
        $requestSpecArr = $request->goodsSpecItems;

        // 排序, 规格少的排在前面
        $sortKeyArr = [];
        foreach ($requestSpecArr as $k => $v) {
            if (!empty($v)){
                $sortKeyArr[$k] = count($v);
            }
        }
        if (empty($sortKeyArr)) {
            return [];
        }
        asort($sortKeyArr);
        $sortSpecArr = [];
        foreach ($sortKeyArr as $key => $val) {
            $sortSpecArr[$key] = $requestSpecArr[$key];
        }
        $specNames = array_keys($sortSpecArr);
        foreach ($specNames as &$v) {
            $v = Spec::where('id', $v)->value('name');
        }
        // ['id' => 'item']
        $specItems = SpecItem::plucK('item', 'id');
        $specGoodsPrice = SpecGoodsPrice::where('goods_id', $request->goods_id ? $request->goods_id : 0)->get();
        $sortSpecArr = combineDika($sortSpecArr); //  获取 规格的 笛卡尔积
        $data = [];
        foreach($sortSpecArr as $key => $specArr) {
            $data[$key]['value'] = '';
            $data[$key]['price'] = 0;
            $data[$key]['stock'] = 0;
            $tempArr = [];
            foreach($specArr as $skey => $itemId) {
                $data[$key]['items'][] = $specItems[$itemId];
                $data[$key]['specs'][] = $specNames[$skey];
                $tempArr[$itemId] = $specNames[$skey].':'.$specItems[$itemId];
            }
            ksort($tempArr);
            $data[$key]['value'] = implode(' ', $tempArr);
            $data[$key]['key'] = implode('_', array_keys($tempArr));
            foreach ($specGoodsPrice as $g) {
                if ($g->key == $data[$key]['key']) {
                    $data[$key]['price'] = $g->price;
                    $data[$key]['stock'] = $g->stock;
                    break;
                }
            }
        }
        return (['specPriceInput' => $data, 'specHeader' => $specNames, 'sortKeyArr' => array_values($sortKeyArr)]);
    }
}
